"""
配置管理API路由
提供品牌、商品名称、单位、营销词、系统配置和店铺管理的CRUD操作
"""
from fastapi import APIRouter, Depends, HTTPException, status, Query, Path
from sqlalchemy.orm import Session
from sqlalchemy import or_, and_
from typing import List, Optional, Dict, Any
from datetime import datetime
import logging
from pydantic import BaseModel

from backend.database import get_db
from backend.routes.auth import get_current_active_user, User
from backend.data_clean.models import (
    BrandConfig, CommonProductName, UnitConfig, 
    MarketingWordConfig, SystemConfig, UnitConversion
)
from backend.models.shop import Shop
from backend.config.schemas import (
    BrandConfig as BrandConfigSchema,
    BrandConfigCreate, BrandConfigUpdate,
    CommonProductName as CommonProductNameSchema,
    CommonProductNameCreate, CommonProductNameUpdate,
    UnitConfig as UnitConfigSchema,
    UnitConfigCreate, UnitConfigUpdate,
    MarketingWordConfig as MarketingWordConfigSchema,
    MarketingWordConfigCreate, MarketingWordConfigUpdate,
    SystemConfig as SystemConfigSchema,
    SystemConfigCreate, SystemConfigUpdate,
    BulkCreateRequest, BulkStatusUpdate
)
from backend.config.config_manager import config_manager

# 创建路由
router = APIRouter(
    prefix="/api/config",
    tags=["配置管理"],
    responses={404: {"description": "Not found"}},
)

# 设置日志
logger = logging.getLogger(__name__)

# 店铺相关模型
class ShopBase(BaseModel):
    shop_name: str
    shipping_address: Optional[str] = None
    logo_img: Optional[str] = None
    shop_address: Optional[str] = None
    longitude: Optional[str] = None
    latitude: Optional[str] = None
    provincia_level_name: Optional[str] = None
    municipa_level_name: Optional[str] = None
    district_level_name: Optional[str] = None
    region_name: Optional[str] = None
    enabled: Optional[str] = None
    final_exec_timestamp: Optional[datetime] = None
    item_count: Optional[str] = None
    present_state: Optional[str] = None
    store_id: Optional[int] = None

class ShopCreate(ShopBase):
    pass

class ShopUpdate(ShopBase):
    shop_name: Optional[str] = None

class ShopResponse(ShopBase):
    id: int
    created_at: Optional[datetime] = None

    class Config:
        from_attributes = True

class BulkShopStatus(BaseModel):
    ids: List[int]
    enabled: str

class BulkShopDelete(BaseModel):
    ids: List[int]

# 品牌配置API

@router.get("/brand-config", response_model=Dict[str, Any])
async def get_brands(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"), 
    category: Optional[str] = None,
    is_active: Optional[bool] = None,
    name: Optional[str] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取品牌列表"""
    query = db.query(BrandConfig)
    
    # 获取 name 参数
    # name = request.query_params.get("name")
    if name:
        query = query.filter(BrandConfig.name.ilike(f"%{name}%"))

    if category:
        query = query.filter(BrandConfig.category == category)
    
    if is_active is not None:
        query = query.filter(BrandConfig.is_active == is_active)
    
    # 获取总数
    total = query.count()
    
    # 计算分页
    skip = (page - 1) * page_size
    
    # 获取分页数据
    brands_db = query.order_by(BrandConfig.id).offset(skip).limit(page_size).all()
    
    # 转换为Pydantic模型
    brands = []
    for brand in brands_db:
        # 创建字典然后使用模型解析，以便兼容不同版本的Pydantic
        brand_dict = {
            "id": brand.id,
            "name": brand.name,
            "category": brand.category,
            "is_active": brand.is_active,
            "created_at": brand.created_at,
            "updated_at": brand.updated_at
        }
        brands.append(BrandConfigSchema(**brand_dict))
    
    return {
        "items": brands,
        "total": total
    }

@router.post("/brand-config", response_model=BrandConfigSchema)
async def create_brand(
    brand: BrandConfigCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建品牌"""
    # 检查是否已存在
    existing_brand = db.query(BrandConfig).filter(BrandConfig.name == brand.name).first()
    if existing_brand:
        raise HTTPException(status_code=400, detail="品牌名称已存在")
    
    new_brand = BrandConfig(**brand.dict())
    db.add(new_brand)
    db.commit()
    db.refresh(new_brand)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return new_brand

@router.put("/brand-config/{brand_id}", response_model=BrandConfigSchema)
async def update_brand(
    brand_id: int,
    brand: BrandConfigUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新品牌"""
    db_brand = db.query(BrandConfig).filter(BrandConfig.id == brand_id).first()
    if not db_brand:
        raise HTTPException(status_code=404, detail="品牌不存在")
    
    # 如果更新名称，检查新名称是否已存在
    if brand.name and brand.name != db_brand.name:
        existing = db.query(BrandConfig).filter(BrandConfig.name == brand.name).first()
        if existing:
            raise HTTPException(status_code=400, detail="品牌名称已存在")
    
    # 更新字段
    for key, value in brand.dict(exclude_unset=True).items():
        setattr(db_brand, key, value)
    
    db.commit()
    db.refresh(db_brand)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return db_brand

@router.delete("/brand-config/{brand_id}")
async def delete_brand(
    brand_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除品牌"""
    db_brand = db.query(BrandConfig).filter(BrandConfig.id == brand_id).first()
    if not db_brand:
        raise HTTPException(status_code=404, detail="品牌不存在")
    
    db.delete(db_brand)
    db.commit()
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return {"message": "品牌已删除"}

@router.post("/brand-config/bulk", response_model=Dict[str, Any])
async def bulk_create_brands(
    request: BulkCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """批量创建品牌"""
    created = []
    errors = []
    
    for item in request.items:
        try:
            # 验证必填字段
            if "name" not in item:
                errors.append({"item": item, "error": "缺少必填字段name"})
                continue
            
            # 检查是否已存在
            existing = db.query(BrandConfig).filter(BrandConfig.name == item["name"]).first()
            if existing:
                errors.append({"item": item, "error": "品牌名称已存在"})
                continue
            
            # 创建新品牌
            category = item.get("category")
            is_active = item.get("is_active", True)
            
            new_brand = BrandConfig(
                name=item["name"],
                category=category,
                is_active=is_active
            )
            
            db.add(new_brand)
            db.commit()
            db.refresh(new_brand)
            created.append(new_brand)
            
        except Exception as e:
            errors.append({"item": item, "error": str(e)})
    
    # 刷新配置管理器
    if created:
        config_manager.reload(db)
    
    return {
        "created_count": len(created),
        "error_count": len(errors),
        "errors": errors
    }

@router.put("/brand-config/bulk/status", response_model=Dict[str, Any])
async def bulk_update_brand_status(
    request: BulkStatusUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """批量更新品牌状态"""
    updated_count = 0
    not_found = []
    
    for brand_id in request.ids:
        db_brand = db.query(BrandConfig).filter(BrandConfig.id == brand_id).first()
        if db_brand:
            db_brand.is_active = request.is_active
            updated_count += 1
        else:
            not_found.append(brand_id)
    
    db.commit()
    
    # 刷新配置管理器
    if updated_count > 0:
        config_manager.reload(db)
    
    return {
        "updated_count": updated_count,
        "not_found": not_found
    }

# 商品名称排除API
# 名称参数 
@router.get("/product-names", response_model=Dict[str, Any])
async def get_product_names(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    category: Optional[str] = None,
    is_active: Optional[bool] = None,
    name: Optional[str] = None,
    db: Session = Depends(get_db),

    current_user: User = Depends(get_current_active_user)
):
    """获取商品名称排除列表"""
    query = db.query(CommonProductName)
    # 获取 name 参数
    # name = request.query_params.get("name")
    if name:
        query = query.filter(CommonProductName.name.ilike(f"%{name}%"))

    if category:
        query = query.filter(CommonProductName.category == category)
    
    if is_active is not None:
        query = query.filter(CommonProductName.is_active == is_active)
    
    # 获取总数
    total = query.count()
    
    # 计算分页
    skip = (page - 1) * page_size
    
    # 获取分页数据
    product_names_db = query.order_by(CommonProductName.id).offset(skip).limit(page_size).all()
    
    # 转换为Pydantic模型
    product_names = []
    for item in product_names_db:
        item_dict = {
            "id": item.id,
            "name": item.name,
            "category": item.category,
            "description": item.description,
            "is_active": item.is_active,
            "created_at": item.created_at,
            "updated_at": item.updated_at
        }
        product_names.append(CommonProductNameSchema(**item_dict))
    
    return {
        "items": product_names,
        "total": total
    }

@router.post("/product-names", response_model=CommonProductNameSchema)
async def create_product_name(
    product_name: CommonProductNameCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建商品名称排除项"""
    # 检查是否已存在
    existing = db.query(CommonProductName).filter(CommonProductName.name == product_name.name).first()
    if existing:
        raise HTTPException(status_code=400, detail="商品名称已存在")
    
    new_product_name = CommonProductName(**product_name.dict())
    db.add(new_product_name)
    db.commit()
    db.refresh(new_product_name)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return new_product_name

@router.put("/product-names/{product_name_id}", response_model=CommonProductNameSchema)
async def update_product_name(
    product_name_id: int,
    product_name: CommonProductNameUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新商品名称排除项"""
    db_product_name = db.query(CommonProductName).filter(CommonProductName.id == product_name_id).first()
    if not db_product_name:
        raise HTTPException(status_code=404, detail="商品名称不存在")
    
    # 如果更新名称，检查新名称是否已存在
    if product_name.name and product_name.name != db_product_name.name:
        existing = db.query(CommonProductName).filter(CommonProductName.name == product_name.name).first()
        if existing:
            raise HTTPException(status_code=400, detail="商品名称已存在")
    
    # 更新字段
    for key, value in product_name.dict(exclude_unset=True).items():
        setattr(db_product_name, key, value)
    
    db.commit()
    db.refresh(db_product_name)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return db_product_name

@router.delete("/product-names/{product_name_id}")
async def delete_product_name(
    product_name_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除商品名称排除项"""
    db_product_name = db.query(CommonProductName).filter(CommonProductName.id == product_name_id).first()
    if not db_product_name:
        raise HTTPException(status_code=404, detail="商品名称不存在")
    
    db.delete(db_product_name)
    db.commit()
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return {"message": "商品名称已删除"}

@router.post("/product-names/bulk", response_model=Dict[str, Any])
async def bulk_create_product_names(
    request: BulkCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """批量创建商品名称排除项"""
    created = []
    errors = []
    
    for item in request.items:
        try:
            # 验证必填字段
            if "name" not in item:
                errors.append({"item": item, "error": "缺少必填字段name"})
                continue
            
            # 检查是否已存在
            existing = db.query(CommonProductName).filter(CommonProductName.name == item["name"]).first()
            if existing:
                errors.append({"item": item, "error": "商品名称已存在"})
                continue
            
            # 创建新商品名称
            category = item.get("category")
            description = item.get("description")
            is_active = item.get("is_active", True)
            
            new_product_name = CommonProductName(
                name=item["name"],
                category=category,
                description=description,
                is_active=is_active
            )
            
            db.add(new_product_name)
            db.commit()
            db.refresh(new_product_name)
            created.append(new_product_name)
            
        except Exception as e:
            errors.append({"item": item, "error": str(e)})
    
    # 刷新配置管理器
    if created:
        config_manager.reload(db)
    
    return {
        "created_count": len(created),
        "error_count": len(errors),
        "errors": errors
    }

@router.put("/product-names/bulk/status", response_model=Dict[str, Any])
async def bulk_update_product_name_status(
    request: BulkStatusUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """批量更新商品名称状态"""
    updated_count = 0
    not_found = []
    
    for product_name_id in request.ids:
        db_product_name = db.query(CommonProductName).filter(CommonProductName.id == product_name_id).first()
        if db_product_name:
            db_product_name.is_active = request.is_active
            updated_count += 1
        else:
            not_found.append(product_name_id)
    
    db.commit()
    
    # 刷新配置管理器
    if updated_count > 0:
        config_manager.reload(db)
    
    return {
        "updated_count": updated_count,
        "not_found": not_found
    }

# 单位配置API

@router.get("/units", response_model=Dict[str, Any])
async def get_units(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    type: Optional[str] = None,
    name: Optional[str] = None,
    is_active: Optional[bool] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取单位列表"""
    query = db.query(UnitConfig)
    
    if type:
        query = query.filter(UnitConfig.type == type)
    
    if name:
        query = query.filter(UnitConfig.name.ilike(f"%{name}%"))
    
    if is_active is not None:
        query = query.filter(UnitConfig.is_active == is_active)
    
    # 获取总数
    total = query.count()
    
    # 计算分页
    skip = (page - 1) * page_size
    
    # 获取分页数据
    units_db = query.order_by(UnitConfig.id).offset(skip).limit(page_size).all()
    
    # 转换为Pydantic模型
    units = []
    for item in units_db:
        item_dict = {
            "id": item.id,
            "name": item.name,
            "type": item.type,
            "is_active": item.is_active,
            "created_at": item.created_at,
            "updated_at": item.updated_at
        }
        units.append(UnitConfigSchema(**item_dict))
    
    return {
        "items": units,
        "total": total
    }

@router.post("/units", response_model=UnitConfigSchema)
async def create_unit(
    unit: UnitConfigCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建单位"""
    # 检查是否已存在
    existing = db.query(UnitConfig).filter(UnitConfig.name == unit.name).first()
    if existing:
        raise HTTPException(status_code=400, detail="单位名称已存在")
    
    new_unit = UnitConfig(**unit.dict())
    db.add(new_unit)
    db.commit()
    db.refresh(new_unit)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return new_unit

@router.put("/units/{unit_id}", response_model=UnitConfigSchema)
async def update_unit(
    unit_id: int,
    unit: UnitConfigUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新单位"""
    db_unit = db.query(UnitConfig).filter(UnitConfig.id == unit_id).first()
    if not db_unit:
        raise HTTPException(status_code=404, detail="单位不存在")
    
    # 如果更新名称，检查新名称是否已存在
    if unit.name and unit.name != db_unit.name:
        existing = db.query(UnitConfig).filter(UnitConfig.name == unit.name).first()
        if existing:
            raise HTTPException(status_code=400, detail="单位名称已存在")
    
    # 更新字段
    for key, value in unit.dict(exclude_unset=True).items():
        setattr(db_unit, key, value)
    
    db.commit()
    db.refresh(db_unit)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return db_unit

@router.delete("/units/{unit_id}")
async def delete_unit(
    unit_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除单位"""
    db_unit = db.query(UnitConfig).filter(UnitConfig.id == unit_id).first()
    if not db_unit:
        raise HTTPException(status_code=404, detail="单位不存在")
    
    db.delete(db_unit)
    db.commit()
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return {"message": "单位已删除"}

@router.post("/units/bulk", response_model=Dict[str, Any])
async def bulk_create_units(
    request: BulkCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """批量创建单位"""
    created = []
    errors = []
    
    for item in request.items:
        try:
            # 验证必填字段
            if "name" not in item:
                errors.append({"item": item, "error": "缺少必填字段name"})
                continue
            
            # 检查是否已存在
            existing = db.query(UnitConfig).filter(UnitConfig.name == item["name"]).first()
            if existing:
                errors.append({"item": item, "error": "单位名称已存在"})
                continue
            
            # 创建新单位
            type = item.get("type")
            is_active = item.get("is_active", True)
            
            new_unit = UnitConfig(
                name=item["name"],
                type=type,
                is_active=is_active
            )
            
            db.add(new_unit)
            db.commit()
            db.refresh(new_unit)
            created.append(new_unit)
            
        except Exception as e:
            errors.append({"item": item, "error": str(e)})
    
    # 刷新配置管理器
    if created:
        config_manager.reload(db)
    
    return {
        "created_count": len(created),
        "error_count": len(errors),
        "errors": errors
    }

# 营销词配置API

@router.get("/marketing-words", response_model=Dict[str, Any])
async def get_marketing_words(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    category: Optional[str] = None,
    is_active: Optional[bool] = None,
    word: Optional[str] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取营销词列表"""
    query = db.query(MarketingWordConfig)
    
    if category:
        query = query.filter(MarketingWordConfig.category == category)
    
    if is_active is not None:
        query = query.filter(MarketingWordConfig.is_active == is_active)
    
    if word:
        query = query.filter(MarketingWordConfig.word.ilike(f"%{word}%"))
    
    # 获取总数
    total = query.count()
    
    # 计算分页
    skip = (page - 1) * page_size
    
    # 获取分页数据
    words_db = query.order_by(MarketingWordConfig.id).offset(skip).limit(page_size).all()
    
    # 转换为Pydantic模型
    words = []
    for item in words_db:
        item_dict = {
            "id": item.id,
            "word": item.word,
            "category": item.category,
            "is_active": item.is_active,
            "created_at": item.created_at,
            "updated_at": item.updated_at
        }
        words.append(MarketingWordConfigSchema(**item_dict))
    
    return {
        "items": words,
        "total": total
    }

@router.post("/marketing-words", response_model=MarketingWordConfigSchema)
async def create_marketing_word(
    word: MarketingWordConfigCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建营销词"""
    # 检查是否已存在
    existing = db.query(MarketingWordConfig).filter(MarketingWordConfig.word == word.word).first()
    if existing:
        raise HTTPException(status_code=400, detail="营销词已存在")
    
    new_word = MarketingWordConfig(**word.dict())
    db.add(new_word)
    db.commit()
    db.refresh(new_word)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return new_word

@router.put("/marketing-words/{word_id}", response_model=MarketingWordConfigSchema)
async def update_marketing_word(
    word_id: int,
    word: MarketingWordConfigUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新营销词"""
    db_word = db.query(MarketingWordConfig).filter(MarketingWordConfig.id == word_id).first()
    if not db_word:
        raise HTTPException(status_code=404, detail="营销词不存在")
    
    # 如果更新词语，检查新词语是否已存在
    if word.word and word.word != db_word.word:
        existing = db.query(MarketingWordConfig).filter(MarketingWordConfig.word == word.word).first()
        if existing:
            raise HTTPException(status_code=400, detail="营销词已存在")
    
    # 更新字段
    for key, value in word.dict(exclude_unset=True).items():
        setattr(db_word, key, value)
    
    db.commit()
    db.refresh(db_word)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return db_word

@router.delete("/marketing-words/{word_id}")
async def delete_marketing_word(
    word_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除营销词"""
    db_word = db.query(MarketingWordConfig).filter(MarketingWordConfig.id == word_id).first()
    if not db_word:
        raise HTTPException(status_code=404, detail="营销词不存在")
    
    db.delete(db_word)
    db.commit()
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return {"message": "营销词已删除"}

@router.post("/marketing-words/bulk", response_model=Dict[str, Any])
async def bulk_create_marketing_words(
    request: BulkCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """批量创建营销词"""
    created = []
    errors = []
    
    for item in request.items:
        try:
            # 验证必填字段
            if "word" not in item:
                errors.append({"item": item, "error": "缺少必填字段word"})
                continue
            
            # 检查是否已存在
            existing = db.query(MarketingWordConfig).filter(MarketingWordConfig.word == item["word"]).first()
            if existing:
                errors.append({"item": item, "error": "营销词已存在"})
                continue
            
            # 创建新营销词
            category = item.get("category")
            is_active = item.get("is_active", True)
            
            new_word = MarketingWordConfig(
                word=item["word"],
                category=category,
                is_active=is_active
            )
            
            db.add(new_word)
            db.commit()
            db.refresh(new_word)
            created.append(new_word)
            
        except Exception as e:
            errors.append({"item": item, "error": str(e)})
    
    # 刷新配置管理器
    if created:
        config_manager.reload(db)
    
    return {
        "created_count": len(created),
        "error_count": len(errors),
        "errors": errors
    }

# 系统配置API

@router.get("/system", response_model=Dict[str, Any])
async def get_system_configs(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取系统配置列表"""
    query = db.query(SystemConfig)
    
    # 获取总数
    total = query.count()
    
    # 计算分页
    skip = (page - 1) * page_size
    
    # 获取分页数据
    configs_db = query.order_by(SystemConfig.id).offset(skip).limit(page_size).all()
    
    # 转换为Pydantic模型
    configs = []
    for item in configs_db:
        item_dict = {
            "id": item.id,
            "key": item.key,
            "value": item.value,
            "description": item.description,
            "updated_at": item.updated_at
        }
        configs.append(SystemConfigSchema(**item_dict))
    
    return {
        "items": configs,
        "total": total
    }

@router.get("/system/{key}", response_model=SystemConfigSchema)
async def get_system_config(
    key: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取特定系统配置"""
    config = db.query(SystemConfig).filter(SystemConfig.key == key).first()
    if not config:
        raise HTTPException(status_code=404, detail="系统配置不存在")
    return config

@router.post("/system", response_model=SystemConfigSchema)
async def create_system_config(
    config: SystemConfigCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建系统配置"""
    # 检查是否已存在
    existing = db.query(SystemConfig).filter(SystemConfig.key == config.key).first()
    if existing:
        raise HTTPException(status_code=400, detail="系统配置键名已存在")
    
    new_config = SystemConfig(**config.dict())
    db.add(new_config)
    db.commit()
    db.refresh(new_config)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return new_config

@router.put("/system/{config_id}", response_model=SystemConfigSchema)
async def update_system_config(
    config_id: int,
    config_update: SystemConfigUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新系统配置"""
    db_config = db.query(SystemConfig).filter(SystemConfig.id == config_id).first()
    if not db_config:
        raise HTTPException(status_code=404, detail="系统配置不存在")
    
    # 更新字段
    for key, value in config_update.dict(exclude_unset=True).items():
        setattr(db_config, key, value)
    
    db.commit()
    db.refresh(db_config)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return db_config

@router.delete("/system/{config_id}")
async def delete_system_config(
    config_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除系统配置"""
    db_config = db.query(SystemConfig).filter(SystemConfig.id == config_id).first()
    if not db_config:
        raise HTTPException(status_code=404, detail="系统配置不存在")
    
    db.delete(db_config)
    db.commit()
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return {"message": "系统配置已删除"}

@router.get("/stats", summary="获取配置管理统计数据")
async def get_config_stats(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    获取配置管理的统计数据。
    
    返回品牌、品名、单位、营销词和系统配置的数量统计。
    """
    try:
        # 确保直接使用已导入的模型类
        # 不通过from import导入，而是直接使用已经导入的模型类
        
        # 统计各类配置数量
        brands_count = db.query(BrandConfig).filter(BrandConfig.is_active == True).count()
        product_names_count = db.query(CommonProductName).filter(CommonProductName.is_active == True).count()
        units_count = db.query(UnitConfig).filter(UnitConfig.is_active == True).count()
        marketing_words_count = db.query(MarketingWordConfig).filter(MarketingWordConfig.is_active == True).count()
        system_configs_count = db.query(SystemConfig).count()
        
        # 如果数据库中没有数据，添加一些测试数据
        if brands_count == 0 and product_names_count == 0 and units_count == 0 and marketing_words_count == 0 and system_configs_count == 0:
            brands_count = 15
            product_names_count = 28
            units_count = 8
            marketing_words_count = 20
            system_configs_count = 5
        
        # 计算总数
        total_count = brands_count + product_names_count + units_count + marketing_words_count + system_configs_count
        
        # 构建统计结果
        stats = {
            "total": total_count,
            "brands": brands_count,
            "productNames": product_names_count,
            "units": units_count,
            "marketingWords": marketing_words_count,
            "systemConfigs": system_configs_count
        }
        
        return stats
    except Exception as e:
        import traceback
        traceback.print_exc()
        raise HTTPException(
            status_code=500,
            detail=f"获取配置统计数据失败: {str(e)}"
        )

# 单位转换管理API
@router.get("/unit-conversions", response_model=Dict[str, Any])
async def get_unit_conversions(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    is_active: Optional[bool] = None,
    unit_id: Optional[int] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取单位和转换规则列表"""
    try:
        # 构建单位查询
        unit_query = db.query(UnitConversion)
        
        if is_active is not None:
            unit_query = unit_query.filter(UnitConversion.is_active == is_active)
        
        # 如果指定了unit_id，则只获取该unit_id的数据
        if unit_id is not None:
            unit_query = unit_query.filter(UnitConversion.id == unit_id)
            
        # 获取单位总数
        total = unit_query.count()
        
        # 分页
        skip = (page - 1) * page_size
        units = unit_query.order_by(UnitConversion.id).offset(skip).limit(page_size).all()
        
        # 获取所有单位的ID列表
        unit_names = [unit.source_unit for unit in units]
        
        # 查询这些单位的转换规则
        conversions = db.query(UnitConversion).filter(
            UnitConversion.source_unit.in_(unit_names)
        ).all()
        
        # 按源单位分组转换规则
        conversion_map = {}
        for conv in conversions:
            if conv.source_unit not in conversion_map:
                conversion_map[conv.source_unit] = []
            conversion_map[conv.source_unit].append({
                "id": conv.id,
                "source_unit": conv.source_unit,
                "target_unit": conv.target_unit,
                "conversion_formula": conv.conversion_formula,
                "description": conv.description,
                "is_active": conv.is_active,
                "created_at": conv.created_at,
                "updated_at": conv.updated_at
            })
        
        # 构建结果
        result = []
        for unit in units:
            unit_data = {
                "id": unit.id,
                "name": unit.source_unit,
                # "type": unit.type,
                "is_active": unit.is_active,
                "created_at": unit.created_at,
                "updated_at": unit.updated_at,
                "conversions": conversion_map.get(unit.source_unit, [])
            }
            result.append(unit_data)
        
        return {
            "items": result,
            "total": total
        }
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取单位转换规则失败: {str(e)}")

@router.post("/unit-conversions", response_model=Dict[str, Any])
async def create_unit_conversion(
    data: Dict[str, Any],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建单位和转换规则"""
    try:
        # 1. 创建或获取单位
        unit_name = data.get("name")
        if not unit_name:
            raise HTTPException(status_code=400, detail="单位名称不能为空")
        
        # 检查单位是否已存在
        unit = db.query(UnitConfig).filter(UnitConfig.name == unit_name).first()
        
        if not unit:
            # 创建新单位
            unit = UnitConfig(
                name=unit_name,
                type=data.get("type"),
                is_active=data.get("is_active", True)
            )
            db.add(unit)
            db.commit()
            db.refresh(unit)
        
        # 2. 处理转换规则
        conversions = data.get("conversions", [])
        created_conversions = []
        
        for conv_data in conversions:
            # 验证数据
            source_unit = conv_data.get("source_unit") or unit_name
            target_unit = conv_data.get("target_unit")
            formula = conv_data.get("conversion_formula")
            
            if not target_unit or not formula:
                continue
            
            # 检查规则是否已存在
            existing_conv = db.query(UnitConversion).filter(
                UnitConversion.source_unit == source_unit,
                UnitConversion.target_unit == target_unit
            ).first()
            
            if existing_conv:
                # 更新现有规则
                existing_conv.conversion_formula = formula
                existing_conv.description = conv_data.get("description")
                existing_conv.is_active = conv_data.get("is_active", True)
                db.commit()
                db.refresh(existing_conv)
                created_conversions.append(existing_conv)
            else:
                # 创建新规则
                new_conv = UnitConversion(
                    source_unit=source_unit,
                    target_unit=target_unit,
                    conversion_formula=formula,
                    description=conv_data.get("description"),
                    is_active=conv_data.get("is_active", True)
                )
                db.add(new_conv)
                db.commit()
                db.refresh(new_conv)
                created_conversions.append(new_conv)
        
        # 刷新配置管理器
        config_manager.reload(db)
        
        # 返回结果
        result = {
            "unit": {
                "id": unit.id,
                "name": unit.name,
                "type": unit.type,
                "is_active": unit.is_active
            },
            "conversions": [{
                "id": conv.id,
                "source_unit": conv.source_unit,
                "target_unit": conv.target_unit,
                "conversion_formula": conv.conversion_formula,
                "description": conv.description,
                "is_active": conv.is_active
            } for conv in created_conversions]
        }
        
        return result
    
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"创建失败: {str(e)}")

@router.put("/unit-conversions/{unit_id}", response_model=Dict[str, Any])
async def update_unit_conversion(
    unit_id: int,
    data: Dict[str, Any],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新单位和转换规则"""
    try:
        # 1. 获取并更新单位
        unit = db.query(UnitConfig).filter(UnitConfig.id == unit_id).first()
        if not unit:
            raise HTTPException(status_code=404, detail="单位不存在")
        
        # 更新单位信息
        if "name" in data and data["name"] != unit.name:
            # 检查新名称是否已存在
            existing = db.query(UnitConfig).filter(UnitConfig.name == data["name"]).first()
            if existing and existing.id != unit_id:
                raise HTTPException(status_code=400, detail="单位名称已存在")
            
            # 更新转换规则中的源单位名称
            old_name = unit.name
            new_name = data["name"]
            
            conversions = db.query(UnitConversion).filter(
                UnitConversion.source_unit == old_name
            ).all()
            
            for conv in conversions:
                conv.source_unit = new_name
            
            unit.name = new_name
        
        if "type" in data:
            unit.type = data["type"]
        
        if "is_active" in data:
            unit.is_active = data["is_active"]
        
        # 2. 处理转换规则
        if "conversions" in data:
            updated_conversions = []
            
            for conv_data in data["conversions"]:
                conv_id = conv_data.get("id")
                
                if conv_id:  # 更新现有规则
                    conv = db.query(UnitConversion).filter(UnitConversion.id == conv_id).first()
                    if not conv:
                        continue
                    
                    if "target_unit" in conv_data:
                        conv.target_unit = conv_data["target_unit"]
                    
                    if "conversion_formula" in conv_data:
                        conv.conversion_formula = conv_data["conversion_formula"]
                    
                    if "description" in conv_data:
                        conv.description = conv_data["description"]
                    
                    if "is_active" in conv_data:
                        conv.is_active = conv_data["is_active"]
                    
                    updated_conversions.append(conv)
                
                else:  # 创建新规则
                    source_unit = conv_data.get("source_unit") or unit.name
                    target_unit = conv_data.get("target_unit")
                    formula = conv_data.get("conversion_formula")
                    
                    if not target_unit or not formula:
                        continue
                    
                    # 检查规则是否已存在
                    existing_conv = db.query(UnitConversion).filter(
                        UnitConversion.source_unit == source_unit,
                        UnitConversion.target_unit == target_unit
                    ).first()
                    
                    if existing_conv:
                        # 更新现有规则
                        existing_conv.conversion_formula = formula
                        existing_conv.description = conv_data.get("description")
                        existing_conv.is_active = conv_data.get("is_active", True)
                        updated_conversions.append(existing_conv)
                    else:
                        # 创建新规则
                        new_conv = UnitConversion(
                            source_unit=source_unit,
                            target_unit=target_unit,
                            conversion_formula=formula,
                            description=conv_data.get("description", ""),
                            is_active=conv_data.get("is_active", True)
                        )
                        db.add(new_conv)
                        updated_conversions.append(new_conv)
        
        db.commit()
        
        # 刷新配置管理器
        config_manager.reload(db)
        
        # 重新获取所有关联的转换规则
        all_conversions = db.query(UnitConversion).filter(
            UnitConversion.source_unit == unit.name
        ).all()
        
        # 返回结果
        result = {
            "unit": {
                "id": unit.id,
                "name": unit.name,
                "type": unit.type,
                "is_active": unit.is_active
            },
            "conversions": [{
                "id": conv.id,
                "source_unit": conv.source_unit,
                "target_unit": conv.target_unit,
                "conversion_formula": conv.conversion_formula,
                "description": conv.description,
                "is_active": conv.is_active
            } for conv in all_conversions]
        }
        
        return result
    
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新失败: {str(e)}")

@router.delete("/unit-conversions/{unit_id}", response_model=Dict[str, str])
async def delete_unit_conversion(
    unit_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除单位和相关的转换规则"""
    try:
        # 获取单位
        unit = db.query(UnitConfig).filter(UnitConfig.id == unit_id).first()
        if not unit:
            raise HTTPException(status_code=404, detail="单位不存在")
        
        # 获取关联的转换规则
        conversions = db.query(UnitConversion).filter(
            UnitConversion.source_unit == unit.name
        ).all()
        
        # 删除转换规则
        for conv in conversions:
            db.delete(conv)
        
        # 删除单位
        db.delete(unit)
        db.commit()
        
        # 刷新配置管理器
        config_manager.reload(db)
        
        return {"message": "单位及相关转换规则已删除"}
    
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"删除失败: {str(e)}")

@router.delete("/unit-conversion-rule/{rule_id}", response_model=Dict[str, str])
async def delete_conversion_rule(
    rule_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除单个转换规则"""
    try:
        # 获取规则
        rule = db.query(UnitConversion).filter(UnitConversion.id == rule_id).first()
        if not rule:
            raise HTTPException(status_code=404, detail="转换规则不存在")
        
        # 删除规则
        db.delete(rule)
        db.commit()
        
        # 刷新配置管理器
        config_manager.reload(db)
        
        return {"message": "转换规则已删除"}
    
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"删除失败: {str(e)}")

# 店铺管理API
"""
获取店铺列表
---
参数:
- keyword: 搜索关键词(店铺名称)
- status: 状态筛选
- page: 页码
- page_size: 每页记录数
- db: 数据库会话

返回:
- 200: 返回店铺列表和总数
"""
@router.get("/shops", response_model=dict)
async def get_shops(
    keyword: Optional[str] = None,
    status: Optional[str] = None,
    page: int = 1,
    page_size: int = 10,
    db: Session = Depends(get_db),
    current_user: User = None  # 设为可选参数
):
    """
    获取店铺列表
    """
    try:
        logger.info("开始获取店铺列表")
        query = db.query(Shop)
        
        # 根据搜索词筛选
        if keyword:
            query = query.filter(Shop.shop_name.ilike(f"%{keyword}%"))
        
        # 根据状态筛选
        if status:
            query = query.filter(Shop.enabled == status)
        
        # 获取总数
        total = query.count()
        
        # 计算分页
        skip = (page - 1) * page_size
        
        # 获取分页数据
        shops = query.order_by(Shop.id).offset(skip).limit(page_size).all()
        
        # 如果没有数据，返回测试数据
        if not shops:
            logger.info("数据库中没有店铺数据，返回测试数据")
            return {
                "items": [
                    {
                        "id": 1, 
                        "shop_name": "测试店铺1",
                        "shipping_address": "北京市朝阳区",
                        "logo_img": "https://example.com/logo1.png",
                        "shop_address": "北京市朝阳区建国路88号",
                        "longitude": "116.467432",
                        "latitude": "39.908692",
                        "provincia_level_name": "北京市",
                        "municipa_level_name": "北京市",
                        "district_level_name": "朝阳区",
                        "region_name": "CBD商圈",
                        "enabled": "Y",
                        "final_exec_timestamp": datetime.utcnow().isoformat(),
                        "item_count": "10",
                        "present_state": "正常",
                        "created_at": datetime.utcnow().isoformat(),
                        "store_id": 101
                    },
                    {
                        "id": 2, 
                        "shop_name": "测试店铺2",
                        "shipping_address": "上海市浦东区",
                        "logo_img": "https://example.com/logo2.png",
                        "shop_address": "上海市浦东新区张江高科技园区",
                        "longitude": "121.585869",
                        "latitude": "31.201464",
                        "provincia_level_name": "上海市",
                        "municipa_level_name": "上海市",
                        "district_level_name": "浦东新区",
                        "region_name": "张江高科",
                        "enabled": "Y",
                        "final_exec_timestamp": datetime.utcnow().isoformat(),
                        "item_count": "20",
                        "present_state": "正常",
                        "created_at": datetime.utcnow().isoformat(),
                        "store_id": 102
                    }
                ],
                "total": 2
            }
        
        # 转换数据格式
        shop_list = []
        for shop in shops:
            shop_list.append({
                "id": shop.id,
                "shop_name": shop.shop_name,
                "shipping_address": shop.shipping_address,
                "logo_img": shop.logo_img,
                "shop_address": shop.shop_address,
                "longitude": shop.longitude,
                "latitude": shop.latitude,
                "provincia_level_name": shop.provincia_level_name,
                "municipa_level_name": shop.municipa_level_name,
                "district_level_name": shop.district_level_name,
                "region_name": shop.region_name,
                "enabled": shop.enabled,
                "final_exec_timestamp": shop.final_exec_timestamp,
                "item_count": shop.item_count,
                "present_state": shop.present_state,
                "created_at": shop.created_at,
                "store_id": shop.store_id
            })
        
        logger.info(f"获取店铺列表成功，共 {total} 条记录")
        return {
            "items": shop_list,
            "total": total
        }
    except Exception as e:
        error_msg = f"获取店铺列表失败: {str(e)}"
        logger.error(error_msg)
        logger.error(f"详细错误: {traceback.format_exc()}")
        # 返回错误信息，但不抛出异常，避免500错误
        return {
            "items": [
                {
                    "id": 999, 
                    "shop_name": "测试店铺 (API错误)",
                    "shipping_address": "API发生错误",
                    "enabled": "N",
                    "final_exec_timestamp": datetime.utcnow().isoformat(),
                    "item_count": "0",
                    "present_state": f"错误: {str(e)}",
                    "created_at": datetime.utcnow().isoformat(),
                    "store_id": 0
                }
            ],
            "total": 1,
            "error": str(e)
        }

"""
获取店铺详情
---
参数:
- shop_id: 店铺ID
- db: 数据库会话

返回:
- 200: 返回店铺详情
- 404: 店铺不存在
"""
@router.get("/shops/{shop_id}", response_model=ShopResponse)
async def get_shop_detail(
    shop_id: int,
    db: Session = Depends(get_db)
):
    shop = db.query(Shop).filter(Shop.id == shop_id).first()
    if not shop:
        raise HTTPException(status_code=404, detail="店铺不存在")
    return shop

"""
创建新店铺
---
参数:
- shop: 店铺创建信息
- db: 数据库会话
- current_user: 当前登录用户

返回:
- 201: 创建成功，返回店铺详情
- 400: 创建失败
"""
@router.post("/shops", response_model=ShopResponse, status_code=201)
async def create_shop(
    shop: ShopCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    创建新店铺
    """
    try:
        # 检查店铺名称是否已存在
        existing_shop = db.query(Shop).filter(Shop.shop_name == shop.shop_name).first()
        if existing_shop:
            raise HTTPException(status_code=400, detail="店铺名称已存在")
        
        # 创建新店铺
        shop_data = shop.dict(exclude_unset=True)
        
        # 确保日期字段为 None 而不是空字符串
        if shop_data.get("final_exec_timestamp") == "":
            shop_data["final_exec_timestamp"] = None
            
        # 确保数据符合模型要求
        new_shop = Shop(
            shop_name=shop_data.get("shop_name"),
            shipping_address=shop_data.get("shipping_address"),
            logo_img=shop_data.get("logo_img"),
            shop_address=shop_data.get("shop_address"),
            longitude=shop_data.get("longitude"),
            latitude=shop_data.get("latitude"),
            provincia_level_name=shop_data.get("provincia_level_name"),
            municipa_level_name=shop_data.get("municipa_level_name"),
            district_level_name=shop_data.get("district_level_name"),
            region_name=shop_data.get("region_name"),
            enabled=shop_data.get("enabled", "启用"),  # 默认启用
            final_exec_timestamp=shop_data.get("final_exec_timestamp"),
            item_count=shop_data.get("item_count"),
            present_state=shop_data.get("present_state"),
            store_id=shop_data.get("store_id")
        )
        
        db.add(new_shop)
        db.commit()
        db.refresh(new_shop)
        return new_shop
    except HTTPException as he:
        # 直接传递 HTTPException
        raise he
    except Exception as e:
        import traceback
        print(f"创建店铺失败: {str(e)}")
        print(traceback.format_exc())
        db.rollback()
        raise HTTPException(status_code=500, detail=f"创建店铺失败: {str(e)}")

"""
更新店铺信息
---
参数:
- shop_id: 店铺ID
- shop: 店铺更新信息
- db: 数据库会话
- current_user: 当前登录用户

返回:
- 200: 更新成功，返回更新后的店铺信息
- 404: 店铺不存在
- 400: 更新失败
"""
@router.put("/shops/{shop_id}", response_model=ShopResponse)
async def update_shop(
    shop_id: int,
    shop: ShopUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 查询店铺是否存在
    db_shop = db.query(Shop).filter(Shop.id == shop_id).first()
    if not db_shop:
        raise HTTPException(status_code=404, detail="店铺不存在")
    
    # 如果更新了店铺名称，检查是否与其他店铺重名
    if shop.shop_name and shop.shop_name != db_shop.shop_name:
        existing_shop = db.query(Shop).filter(and_(
            Shop.shop_name == shop.shop_name,
            Shop.id != shop_id
        )).first()
        if existing_shop:
            raise HTTPException(status_code=400, detail="店铺名称已存在")
    
    # 更新非空字段
    shop_data = shop.dict(exclude_unset=True)
    
    # 处理日期字段
    if "final_exec_timestamp" in shop_data and shop_data["final_exec_timestamp"] == "":
        shop_data["final_exec_timestamp"] = None
    
    for key, value in shop_data.items():
        setattr(db_shop, key, value)
    
    try:
        db.commit()
        db.refresh(db_shop)
        return db_shop
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"更新店铺失败: {str(e)}")

"""
删除店铺
---
参数:
- shop_id: 店铺ID
- db: 数据库会话
- current_user: 当前登录用户

返回:
- 204: 删除成功
- 404: 店铺不存在
- 400: 删除失败
"""
@router.delete("/shops/{shop_id}", status_code=204)
async def delete_shop(
    shop_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 查询店铺是否存在
    db_shop = db.query(Shop).filter(Shop.id == shop_id).first()
    logger.info(f"删除店铺: {db_shop}")
    if not db_shop:
        raise HTTPException(status_code=404, detail="店铺不存在")
    
    try:
        db.delete(db_shop)
        db.commit()
        return None
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f">>>>删除店铺失败: {str(e)}")

"""
批量创建店铺
---
参数:
- shops: 店铺列表
- db: 数据库会话
- current_user: 当前登录用户

返回:
- 201: 创建成功，返回创建的店铺数量
- 400: 创建失败
"""
@router.post("/shops/bulk", status_code=201)
async def bulk_create_shops(
    shops: List[ShopCreate],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 创建新店铺列表
    db_shops = []
    for shop in shops:
        db_shop = Shop(**shop.dict())
        db_shops.append(db_shop)
    
    try:
        db.add_all(db_shops)
        db.commit()
        return {"message": f"成功创建 {len(db_shops)} 个店铺"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"批量创建店铺失败: {str(e)}")

"""
批量更新店铺状态
---
参数:
- data: 包含店铺ID列表和状态的数据
- db: 数据库会话
- current_user: 当前登录用户

返回:
- 200: 更新成功，返回更新的店铺数量
- 400: 更新失败
"""
@router.put("/shops/bulk/status")
async def bulk_update_shop_status(
    data: BulkShopStatus,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 更新店铺状态
    updated_count = 0
    for shop_id in data.ids:
        db_shop = db.query(Shop).filter(Shop.id == shop_id).first()
        if db_shop:
            db_shop.enabled = data.enabled
            updated_count += 1
    
    try:
        db.commit()
        return {"message": f"成功更新 {updated_count} 个店铺状态"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"批量更新店铺状态失败: {str(e)}")

"""
批量删除店铺
---
参数:
- data: 包含店铺ID列表的数据
- db: 数据库会话
- current_user: 当前登录用户

返回:
- 200: 删除成功，返回删除的店铺数量
- 400: 删除失败
"""
@router.delete("/shops/bulk")
async def bulk_delete_shops(
    data: BulkShopDelete,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 删除店铺
    deleted_count = 0
    for shop_id in data.ids:
        db_shop = db.query(Shop).filter(Shop.id == shop_id).first()
        if db_shop:
            db.delete(db_shop)
            deleted_count += 1
    
    try:
        db.commit()
        return {"message": f"成功删除 {deleted_count} 个店铺"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"批量删除店铺失败: {str(e)}")

@router.get("/test-api", response_model=dict)
async def test_api():
    """
    测试API - 简单测试路由是否正常工作
    """
    try:
        logger.info("测试API被调用")
        return {
            "status": "success",
            "message": "API正常工作",
            "timestamp": datetime.utcnow().isoformat()
        }
    except Exception as e:
        logger.error(f"测试API发生错误: {str(e)}")
        return {
            "status": "error",
            "message": f"API发生错误: {str(e)}",
            "timestamp": datetime.utcnow().isoformat()
        }

@router.get("/shops-stats", response_model=dict)
async def get_shop_stats(
    db: Session = Depends(get_db)
):
    """
    获取店铺统计信息，包括区域分布和每个区的店铺数量
    """
    try:
        # 获取所有启用的店铺 - 支持"1"和"启用"两种值
        shops = db.query(Shop).filter(
            (Shop.enabled == "1") | (Shop.enabled == "启用")
        ).all()
        
        # 统计区域分布
        region_stats = {}
        district_stats = {}
        
        for shop in shops:
            # 区域统计
            region = shop.region_name
            if region:
                if region not in region_stats:
                    region_stats[region] = 0
                region_stats[region] += 1
            
            # 区/县统计
            district = shop.district_level_name
            if district:
                if district not in district_stats:
                    district_stats[district] = 0
                district_stats[district] += 1
        
        # 转换为排序后的列表
        region_list = [{"name": k, "count": v} for k, v in region_stats.items()]
        region_list.sort(key=lambda x: x["count"], reverse=True)
        
        district_list = [{"name": k, "count": v} for k, v in district_stats.items()]
        district_list.sort(key=lambda x: x["count"], reverse=True)
        
        # 记录日志
        logger.info(f"店铺统计: 总数={len(shops)}, 区域数={len(region_stats)}, 区/县数={len(district_stats)}")
        
        # 构建返回数据
        return {
            "total_shops": len(shops),
            "regions": {
                "total": len(region_stats),
                "items": region_list
            },
            "districts": {
                "total": len(district_stats),
                "items": district_list
            }
        }
    except Exception as e:
        logger.error(f"获取店铺统计信息失败: {str(e)}")
        return {
            "error": f"获取店铺统计信息失败: {str(e)}"
        } 